package com.fifth.commodity.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fifth.commodity.feign.BusinessFeign;
import com.fifth.commodity.feign.CollectionFeign;
import com.fifth.commodity.feign.OrderFeign;
import com.fifth.commodity.untils.WebUtils;
import com.fifth.commodity.vo.GoodsVo;
import com.fifth.commodity.vo.QianGetGoodsVo;
import com.fifth.commodity.vo.StateVo;
import com.fifth.commodity.vo.StatusVo;
import com.fifth.common.pojo.dto.CommonResult;
import com.fifth.common.pojo.entity.*;
import com.fifth.commodity.mapper.GoodsMapper;
import com.fifth.commodity.service.GoodsService;
import com.fifth.common.pojo.vo.SelectBusinessInfoByGNameVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class GoodsServiceImpl implements GoodsService {
    @Autowired
    private GoodsMapper goodsMapper;

    @Resource
    private CollectionFeign collectionFeign;

    @Resource
    private OrderFeign orderFeign;

    @Resource
    private BusinessFeign businessFeign;

    @Autowired
    private StringRedisTemplate redisTemplate;

    /*
    *
    *
    * 获取描述信息
    * */
    @Override
    public String goodsid(String id) {
        Goods goods = goodsMapper.selectById(id);
        String remark = goods.getRemark();
        return remark;
    }
    /*
    *
    * 商品名称
    *
    * */
    @Override
    public String goodsidname(String id) {
        Goods goods = goodsMapper.selectById(id);
        String gname = goods.getGname();
        return gname;
    }
    /*
    * 查询所有
    * */
    @Override
    public CommonResult GoodsAll(Goods goods /*,String rid*/){
         /*HttpServletRequest request = WebUtils.getRequest();
        String token = request.getHeader("token");
        Map mp = JSON.parseObject(stringRedisTemplate.opsForValue().get(token), Map.class);
        Object rid = mp.get("rid");*/
        /*int id = Integer.parseInt(rid);
        if (id==1){
            System.out.println(rid);
            PageHelper.startPage(currentPage,pageSize);*/
            List<Goods> goods1 = goodsMapper.selectAll(goods);
            //PageInfo pageInfo = new PageInfo(goods1);
            if (goods1!=null){
                return new CommonResult(2000,"查询成功",goods1);
            }else {
                return new CommonResult(5000,"查询失败",null);
            }
        /*}else {
            return new CommonResult(5000,"没有权限",null);
        }*/
    }
    /*
    * 删除
    * */
    @Override
    public CommonResult GoodsDelete(String id) {
        int i = goodsMapper.deleteById(id);
        return new CommonResult(2000,"删除成功",i);
    }
    /*
    * 添加
    * */
    @Override
    public CommonResult GoodsInsert(Goods goods) {
        int insert = goodsMapper.insert(goods);
        return new CommonResult(2000,"添加成功",insert);
    }
    /*
    * 修改
    * */
    @Override
    public CommonResult GoodsUpdate(Goods goods) {
        int i = goodsMapper.updateById(goods);
        return new CommonResult(2000,"修改成功",i);
    }

    /*
    * 根据id查询
    * */
    @Override
    public CommonResult GoodsSelectById(String id){
        Goods goods = goodsMapper.selectById(id);
        return new CommonResult(2000,"查询成功",goods);
    }

    /**
     * 根据条件查询所有商品
     * @param pageCurrent
     * @param pageSize
     * @param goodsVo
     * @return
     */
    @Override
    public CommonResult findAllGoods(Integer pageCurrent, Integer pageSize, GoodsVo goodsVo) {
        QueryWrapper<Goods> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(StringUtils.isNotBlank(goodsVo.getGoodsname()),"gname", goodsVo.getGoodsname());
        queryWrapper.eq(StringUtils.isNotBlank(goodsVo.getSortid()),"goods.sortid", goodsVo.getSortid());
        queryWrapper.eq(StringUtils.isNotBlank(goodsVo.getBusinessid()),"bid", goodsVo.getBusinessid());
        if (goodsVo.getState()!=null){
            queryWrapper.eq("goods.state",goodsVo.getState());
        }
        IPage<Goods> page = new Page<>(pageCurrent,pageSize);
        if (goodsVo.getGoodsname()==null && goodsVo.getSortid()==null && goodsVo.getBusinessid()==null&&goodsVo.getState()==null){
            queryWrapper = null;
        }
        IPage<Goods> goodsIPage = goodsMapper.findAllGoods(page,queryWrapper);

        return new CommonResult(2000,"查询成功",goodsIPage);
    }

    /**
     * 根据商品id和status修改订单状态
     * @param statusVo
     * @return
     */
    @Override
    public CommonResult upadteStatus(StatusVo statusVo) {
        QueryWrapper<Goods> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id",statusVo.getId());
        Goods goods = new Goods();
        goods.setStatus(statusVo.getStatus());
        int update = goodsMapper.update(goods, queryWrapper);
        if (update==1){
            return new CommonResult(2000,"修改成功",null);
        }else {
            return new CommonResult(5000,"修改失败",null);
        }
    }

    /**
     * 修改商品的审核状态
     * @param stateVo
     * @return
     */
    @Override
    public CommonResult updateState(StateVo stateVo) {
        Goods goods = new Goods();
        goods.setCheckContent(stateVo.getCheckContent());
        goods.setState(stateVo.getState());
        QueryWrapper<Goods> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id",stateVo.getId());
        int update = goodsMapper.update(goods, queryWrapper);
        if (update==1){
            return new CommonResult(2000,"修改状态成功",null);
        }
        return new CommonResult(5000,"修改失败",null);
    }

    /**
     * 根据goodsid查询商品信息
     * @param id
     * @return
     */
    @Override
    public CommonResult findGoodsByGoodsid(String id) {
        Goods goods = goodsMapper.findGoodsByGoodsid(id);
        return new CommonResult(2000,"查询成功",goods);
    }

    /**
     * 根据goodsid查询成交量
     * @param goodsid
     * @return
     */
    @Override
    public CommonResult getGoodsSellNum(String goodsid) {
        Integer goodsSellNum = orderFeign.getGoodsSellNum(goodsid);
        return new CommonResult(2000,"查询成功",goodsSellNum);
    }

    @Override
    public CommonResult isGoodsCollection(String id) {
        //获取userid
        HttpServletRequest requestToken = WebUtils.getRequest();
        //获取token
        String token = requestToken.getHeader("token");
        //根据token获取userid
        Map userMap = JSON.parseObject(redisTemplate.opsForValue().get(token), Map.class);
        String userid;
        if (userMap != null && userMap.containsKey("user")) {
            JSONObject user = (JSONObject) userMap.get("user");
            userid = user.getString("id");
        } else {
            return new CommonResult(4000, "登录失效,请登录后再购买", null);
        }
        Collection goodsCollection = collectionFeign.isGoodsCollection(id, userid);
        if (goodsCollection==null || goodsCollection.getId()==null || goodsCollection.getId().equals("")){
            return new CommonResult(2000,"查询成功",1);
        }
        return new CommonResult(2000,"查询成功",0);
    }

    /**
     * 修改收藏状态
     * @param id
     * @param status
     * @return
     */
    @Override
    public CommonResult changeCollectionStatus(String id, Integer status) {
        //获取userid
        HttpServletRequest requestToken = WebUtils.getRequest();
        //获取token
        String token = requestToken.getHeader("token");
        //根据token获取userid
        Map userMap = JSON.parseObject(redisTemplate.opsForValue().get(token), Map.class);
        String userid;
        if (userMap != null && userMap.containsKey("user")) {
            JSONObject user = (JSONObject) userMap.get("user");
            userid = user.getString("id");
        } else {
            return new CommonResult(4000, "登录失效,请登录后再试", null);
        }
        if (status==1){
            //删除收藏
            CommonResult commonResult = collectionFeign.deleteCollection(id,userid);
            if (commonResult.getCode()==2000){
                return new CommonResult(2000,"取消收藏成功",null);
            }
            return new CommonResult(5000,"更改收藏状态失败,请稍后再试",null);
        }else {
            //添加收藏
            Collection collection = new Collection();
            collection.setGoodsid(id);
            CommonResult commonResult = collectionFeign.insertCollection(id,userid);
            if (commonResult.getCode()==2000){
                return new CommonResult(2000,"收藏成功",0);
            }
            return new CommonResult(5000,"更改收藏状态失败,请稍后再试",1);
        }

    }

    /**
     * 根据goodsid判断当前用户是否关注该店铺
     * @param bid
     * @return
     */
    @Override
    public CommonResult isCollectionBusiness(String bid) {
        //获取userid
        HttpServletRequest requestToken = WebUtils.getRequest();
        //获取token
        String token = requestToken.getHeader("token");
        //根据token获取userid
        Map userMap = JSON.parseObject(redisTemplate.opsForValue().get(token), Map.class);
        String userid;
        if (userMap != null && userMap.containsKey("user")) {
            JSONObject user = (JSONObject) userMap.get("user");
            userid = user.getString("id");
        } else {
            return new CommonResult(4000, "登录失效,请登录后再试", null);
        }
        Collection collection = collectionFeign.selectBidAUid(bid,userid);
        if (collection==null || collection.getId()==null || collection.getId().equals("")){
            //未关注该店铺返回0
            return new CommonResult(2000,"查询成功",1);
        }else {
            return new CommonResult(2000,"查询成功",0);
        }
    }

    /**
     * 点击关注/取关
     * @param bid
     * @param status
     * @return
     */
    @Override
    public CommonResult changeGuanzhu(String bid, Integer status) {
        //获取userid
        HttpServletRequest requestToken = WebUtils.getRequest();
        //获取token
        String token = requestToken.getHeader("token");
        //根据token获取userid
        Map userMap = JSON.parseObject(redisTemplate.opsForValue().get(token), Map.class);
        String userid;
        if (userMap != null && userMap.containsKey("user")) {
            JSONObject user = (JSONObject) userMap.get("user");
            userid = user.getString("id");
        } else {
            return new CommonResult(4000, "登录失效,请登录后再试", null);
        }
        if (status==0){
            //取消关注
            CommonResult commonResult = collectionFeign.deleteByBid(bid, userid);
            if (commonResult.getCode().equals(2000)){
                return new CommonResult(2000,"取消关注成功",1);
            }
        }else {
            //添加关注
            CommonResult commonResult = collectionFeign.insertBid(bid, userid);
            if (commonResult.getCode().equals(2000)){
                return new CommonResult(2000,"关注成功",0);
            }
        }
        return new CommonResult(5000,"后端错误",null);
    }

    /**
     * 根据uid获取所有收获地址
     * @return
     */
    @Override
    public CommonResult getAllAddr() {
        //获取userid
        HttpServletRequest requestToken = WebUtils.getRequest();
        //获取token
        String token = requestToken.getHeader("token");
        //根据token获取userid
        Map userMap = JSON.parseObject(redisTemplate.opsForValue().get(token), Map.class);
        String userid;
        if (userMap != null && userMap.containsKey("user")) {
            JSONObject user = (JSONObject) userMap.get("user");
            userid = user.getString("id");
        } else {
            return new CommonResult(4000, "登录失效,请登录后再试", null);
        }
        CommonResult byUId = collectionFeign.findByUId(userid);
        return byUId;
    }

    /**
     * 模糊查询商品名查询对应店铺信息
     * @param gname
     * @return
     */
    @Override
    public List<ZoneBusiness> findBusinessByGName(String gname) {
        List<BusinessInfo> businesByGNmae = goodsMapper.findBusinesByGNmae(gname);
        List<ZoneBusiness> list  = new ArrayList<>();
        for (BusinessInfo businessInfo : businesByGNmae) {
            ZoneBusiness z = new ZoneBusiness();
            z.setBusinessInfo(businessInfo);
            list.add(z);
        }
        return list;
    }

    /**
     * 根据店铺id获取所有商品信息分页+条件
     * @param currentPage
     * @param pageSize
     * @param goodsVo
     * @return
     */
    @Override
    public CommonResult selectAllGoodsInfoByBusinessId(Integer currentPage, Integer pageSize, QianGetGoodsVo goodsVo) {
        //获取userid
        HttpServletRequest requestToken = WebUtils.getRequest();
        //获取token
        String token = requestToken.getHeader("token");
        //根据token获取userid
        Map userMap = JSON.parseObject(redisTemplate.opsForValue().get(token), Map.class);
        String userid;
        if (userMap != null && userMap.containsKey("user")) {
            JSONObject user = (JSONObject) userMap.get("user");
            userid = user.getString("id");
        } else {
            return new CommonResult(4000, "登录失效,请登录后再试", null);
        }
        QueryWrapper<Goods> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("shangjia.id",userid);
        if (goodsVo.getGoodsname()!=null){
            queryWrapper.like("goods.gname",goodsVo.getGoodsname());
        }
        if (goodsVo.getState()!=null){
            queryWrapper.eq("goods.state",goodsVo.getState());
        }
        if (goodsVo.getStatus()!=null){
            queryWrapper.eq("goods.status",goodsVo.getStatus());
        }
        IPage<Goods> page = new Page<>(currentPage,pageSize);
        IPage<Goods> goodsIPage = goodsMapper.selectGoodsInfoByBusinessId(page,queryWrapper);
        return new CommonResult(2000,"查询成功",goodsIPage);
    }

    /**
     * 根据id删除商品
     * @param id
     * @return
     */
    @Override
    public CommonResult deleteGoodsById(String id) {
        int i = goodsMapper.deleteById(id);
        if (i==1){
            return new CommonResult(2000,"success",null);
        }
        return new CommonResult(5000,"删除失败",null);
    }

    /**
     * 添加商品
     * @param goods
     * @return
     */
    @Override
    @Transactional
    public CommonResult addGoods(Goods goods) {
        //获取userid
        HttpServletRequest requestToken = WebUtils.getRequest();
        //获取token
        String token = requestToken.getHeader("token");
        //根据token获取userid
        Map userMap = JSON.parseObject(redisTemplate.opsForValue().get(token), Map.class);
        String userid;
        if (userMap != null && userMap.containsKey("user")) {
            JSONObject user = (JSONObject) userMap.get("user");
            userid = user.getString("id");
        } else {
            return new CommonResult(4000, "登录失效,请登录后再试", null);
        }
        goods.setBid(userid);
        goods.setStatus(1);
        goods.setState(2);
        int insert = goodsMapper.insert(goods);
        if (insert==1){
            //添加库存
            orderFeign.addStock(goods.getId(),goods.getTotalnum(),goods.getPrice());
            return new CommonResult(2000,"添加成功",null);
        }
        return new CommonResult(5000,"添加失败",null);
    }

    /**
     * 修改商品信息
     * @param goods
     * @return
     */
    @Override
    @Transactional
    public CommonResult updateGoods(Goods goods) {
        QueryWrapper<Goods> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id",goods.getId());
        goods.setState(2);
        goods.setStatus(1);
        int update = goodsMapper.update(goods, queryWrapper);
        if (update==1){
            //修改库存
            orderFeign.updateStock(goods.getId(),goods.getSellnum(),goods.getTotalnum());
            return new CommonResult(2000,"修改成功",null);
        }
        return new CommonResult(5000,"修改失败",null);
    }

    /**
     * 根据店铺id查询所有商品信息及店铺信息
     * @param pageCurrent
     * @param pageSize
     * @param bid
     * @return
     */
    @Override
    public CommonResult findGoodsByBid(Integer pageCurrent, Integer pageSize, String bid) {
        BusinessInfo businessInfo = businessFeign.selectmarchant(bid);
        IPage<Goods> page = new Page<>(pageCurrent, pageSize);
        QueryWrapper<Goods> wrapper = new QueryWrapper<>();
        wrapper.eq("bid",bid);
        wrapper.eq("status",0);
        IPage<Goods> goodsIPage = goodsMapper.selectPage(page, wrapper);
        Map<String,Object> map = new HashMap<>();
        map.put("business",businessInfo);
        map.put("goods",goodsIPage);

        return new CommonResult(2000,"查询成功",map);
    }

    /**
     * 检查商品上下架状态
     * @param goodsid
     * @return
     */
    @Override
    public Integer checkGoodsStatus(String goodsid) {
        Goods goods = goodsMapper.selectById(goodsid);
        return goods.getStatus();
    }

    /**
     * 获取店铺类别
     * @return
     */
    @Override
    public CommonResult getgetSort() {
        //获取userid
        HttpServletRequest requestToken = WebUtils.getRequest();
        //获取token
        String token = requestToken.getHeader("token");
        //根据token获取userid
        Map userMap = JSON.parseObject(redisTemplate.opsForValue().get(token), Map.class);
        String userid;
        if (userMap != null && userMap.containsKey("user")) {
            JSONObject user = (JSONObject) userMap.get("user");
            userid = user.getString("id");
        } else {
            return new CommonResult(4000, "登录失效,请登录后再试", null);
        }
        Map<String, String> sort = goodsMapper.getSort(userid);
        return new CommonResult(2000,"查询成功",sort);
    }

}
